package Test;

import com.jcraft.jsch.*;

import java.io.IOException;
import java.io.InputStream;

public class SSHClient {
    private final String host;
    private final int port;
    private final String username;
    private final String password;
    private Session session;

    public SSHClient(String host, int port, String username, String password) {
        this.host = host;
        this.port = port;
        this.username = username;
        this.password = password;
    }

    public void connect() throws JSchException {
        JSch jsch = new JSch();
        session = jsch.getSession(username, host, port);
        session.setPassword(password);
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();
    }

    public void disconnect() {
        session.disconnect();
    }

    public String executeCommand(String command) throws JSchException, IOException {
        ChannelExec channel = (ChannelExec) session.openChannel("exec");
        channel.setCommand(command);
        InputStream commandOutput = channel.getInputStream();
        channel.connect();
        StringBuilder outputBuffer = new StringBuilder();
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = commandOutput.read(buffer)) != -1) {
            outputBuffer.append(new String(buffer, 0, bytesRead));
        }
        channel.disconnect();
        return outputBuffer.toString();
    }

    public void executeSftp(String remoteFilePath,String destFilePath) throws JSchException, SftpException {
        ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
        channel.connect();
        // 读取文件内容
        channel.get(remoteFilePath, destFilePath);
        channel.disconnect();
        session.disconnect();
    }
}